package controller.member;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.jdo.Member;
import model.persistence.PMF;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 4215508913184884436L;

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Member.class);
		
		q.setFilter("email == emailParam && password == passwordParam");
		q.declareParameters("Object emailParam, String passwordParam");
		try {
		  List<Member> results = (List<Member>) q.execute(req.getParameter("email"), req.getParameter("pass"));
		  
		  if (results.isEmpty())
			  resp.getWriter().print("emailOrPasswordIsWrong");
		  else {
			  HttpSession session = req.getSession();
			  Member mem = results.get(0);
			  
			  session.setAttribute("id", String.valueOf(mem.getKey().getId()));
			  session.setAttribute("nickname", mem.getNickname());
		  }
		} finally {
		  q.closeAll();
		  pm.close();
		}
	}
}
